package com.oneinlet

import io.netty.buffer.Unpooled
import java.nio.charset.Charset
import java.util.*

/**
 * Created by WangZiHe on 2019/1/7/007
 * QQ/WeChat:648830605
 * QQ-Group:368512253
 * Blog:www.520code.net
 * Github:https://github.com/yancheng199287
 */
data class Pandora(
        var msgType: Byte? = null,
        var channelId: String = "",
        var content: String? = null,
        var data: ByteArray? = null
) {

    companion object {
        val MAX_FRAME_LENGTH = 10 * 1024 * 1024
        val LENGTH_FIELD_OFFSET = 0
        val LENGTH_FIELD_LENGTH = 4
        val LENGTH_ADJUSTMENT = 0   // netty 会计算容器的总长度+LENGTH_FIELD_LENGTH4   本来容量593   +4  =597  发现对比 读取的593小于计算的597 返回null
        //解决办法，我们在长度值中去掉长度占用字节4   或者 指定修正值为-4
        val INITIAL_BYTES_TO_STRIP = 0


        private val MSG_TYPE_LENGTH = 1 // 消息类型的字节数
        private val CONTENT_LENGTH = 4 //记录内容长度的字节数
        val CHANNEL_ID_LENGTH = 60 //通道ID字符长度 也是字节
        val HEADER_LENGTH = CONTENT_LENGTH + MSG_TYPE_LENGTH + CHANNEL_ID_LENGTH
        val CHARSET = Charset.forName("UTF-8")
    }


    override fun toString(): String {
        return "Pandora(msgType=${getExplainFromType(msgType!!)}, channelId=$channelId, content=$content,dataString=${String(data!!, CHARSET)}, data=${Arrays.toString(data)})"
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false
        other as Pandora
        if (msgType != other.msgType) return false
        if (channelId != other.channelId) return false
        if (content != other.content) return false
        if (!Arrays.equals(data, other.data)) return false
        return true
    }

    override fun hashCode(): Int {
        var result: Int = msgType!!.toInt()
        result = 31 * result + (channelId.hashCode() ?: 0)
        result = 31 * result + (content?.hashCode() ?: 0)
        result = 31 * result + (data?.contentHashCode() ?: 0)
        return result
    }


    enum class MsgType(val type: Byte, val explain: String) {
        REQUEST_AUTH(0x00, "请求认证"),
        SUCCESS_AUTH(0x01, "认证成功"),
        FAILED_AUTH(0x02, "认证失败"),
        SEND_MSG_FROM_USER_TO_YCSERVER(0x03, "用户向YCSERVER发送消息"),
        SEND_MSG_FROM_YCLINET_TO_YCSERVER(0x04, "YC客户端向YCSERVER发送消息"),

        DISCONNECT_FROM_YCLINET_TO_YCSERVER(0x05, "YC客户端向YCSERVER发送断开连接请求"),
        SEND_MSG_FROM_YCSERVER_TO_YCLINET(0x06, "YCSERVER向YCLINET发送消息"),

        // 适用于长链接，用户通道断开 发送消息给YC客户端 清除缓存
        DISCONNECT_FROM_APPSERVER_TO_YCLINET(0x05, "APP服务端通知YC客户端断开连接请求，删除无用通道缓存"),

        HEARTBEAT_PACKET(0x07, "维持心跳数据包"),
    }

    fun getExplainFromType(type: Byte): String? {
        MsgType.values().iterator().forEach {
            if (type == it.type) {
                return it.explain
            }
        }
        return null
    }


}